{% extends "base.html" %}
{% block base.html %}
    <style type="text/css">
        #login {
            width: 360px;
            margin: 0 auto;
        }
    </style>
    <div class="card hoverable" id="login">
    <div class="card-title center" style="background-color: #26a69a;">
        管理员登录入口
    </div>
    <div class="card-content">
        <form class="col s-12" id="login-form">
            {% csrf_token %}
            <div class="row">
                <div class="input-field col s12">
                    <i class="material-icons prefix">account_circle</i>
                    <input type="text" id="username" class="validate" maxlength="8" required onchange="isEmpty()">
                    <label for="username">用户名</label>
                </div>
            </div>
            <div class="row">
                <div class="input-field col s12">
                    <i class="material-icons prefix">visibility_off</i>
                    <input type="password" id="password" class="validate" maxlength="16" required onchange="isEmpty()">
                    <label for="password">密码</label>
                </div>
            </div>
            <div class="center">
                <button type="button" class="waves-effect waves-light btn" id="login-button" disabled><i class="material-icons right">send</i>登录</button>
                <button type="reset" class="waves-effect waves-light btn" id="reset-button" disabled><i class="material-icons left">refresh</i>重置</button>
            </div>
        </form>
    </div>
</div>

<script type="text/javascript">
    function isEmpty() {
        if ($('#username').val() !== "" && $('#password').val() !== "") {
            $('#login-button').removeAttr('disabled');
            $('#reset-button').removeAttr('disabled');
        }
        else {
            $('#login-button').attr({"disabled":"disabled"});
            $('#reset-button').attr({"disabled":"disabled"});
        }
    }
    document.getElementById('login-button').onclick = function () {
        $.ajax({
            type: "POST",
            url: "/api_login/",
            data: {
                username: $("#username").val(),
                password: $("#password").val()
            },
            dataType: "json",
            success: function (data) {
                if (data.status === '1') {
                    alert('登录成功');
                    window.location.href=document.referrer||host + "";
                }
                else if (data.status === '0') {
                    alert('很显然你正在做一些不该做的事情')
                }
            },
            error: function (jpXHR) {
                alert("Status Code: " + jpXHR.status);
            },
        });
    };
    </script>
{% endblock %}